import React, { Component } from 'react'

import { Flex, Toast } from 'antd-mobile'

import { getCurrentCity, API } from '../../utils'

// import { List, AutoSizer, WindowScroller,  InfiniteLoader } from 'react-virtualized'
import List from 'react-virtualized/dist/commonjs/List'
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer'
import WindowScroller from 'react-virtualized/dist/commonjs/WindowScroller'
import InfiniteLoader from 'react-virtualized/dist/commonjs/InfiniteLoader'

import classNames from 'classnames'

import HouseItem from '../../components/HouseItem'

import SearcHearch from '../../components/searchHeader'
import Filter from './components/Filter'
import Sticky from '../../components/Sticky'
import NoHouse from '../../components/NoHouse'

import styles from './index.module.scss'

// 房源列表中每一项的高度
const ROW_HEIGHT = 120
export default class HomeList extends Component {
  state = {
    cityName: '',
    // 房源列表数据
    list: [],
    count: 0,
    // 房源数据是否加载完成
    isLoaded: false,
    // houseList组件是否overflow: hiden, 当hiden时列表不可滚动，菜单栏打开时hiden
    isFixed: false
  }
  async componentDidMount() {
    let { label, value } = await getCurrentCity()
    this.setState({
      cityName: label
    })
    this.cityId = value
    this.onFilter({})
  }
  onFilter = async filters => {
    // 每次加载数据前都让页面滚动到ding部
    window.scrollTo(0, 0)
    this.filters = filters
    // console.log('filters', filters);

    this.setState({isLoaded: false})
    // 开启loading提示效果
    Toast.loading('加载中...', 0)
    const {data: {body: {count, list}}} = await API.get('/houses', {
      params: {
        ...filters,
        cityId: this.cityId
      }
    })
    // console.log(count, list);

    //关闭loading提示
    Toast.hide()
    if (count) Toast.info(`共找到${count}套房源`, 1.5)
    this.setState({ list, count, isLoaded: true})
  }
  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    style, // Style object to be applied to row (to position it)
  }) => {
    const item = this.state.list[index]
    if (!item) {
      return (
        <div key={key} style={style}>
          <div className={styles.loading}></div>
        </div>
      )
    }
    return (
      <div key={key} style={style} className="city">
        {/* 在快速滚动列表时，会报错，因为滚动过快导致发送请求还没拿到数据就渲染houseItem组件,此时item为undefined */}
        {/* 解决方式： 条件渲染，item有数据就渲染houseItem组件，没有数据渲染一个占位符 */}
        <HouseItem {...item}></HouseItem>
      </div>
    )
  }
  // 判断列表中的行数据是否加载完成
  isRowLoaded = ({ index }) => {
    return !!this.state.list[index]
  }
  loadMoreRows = ({ startIndex, stopIndex }) => {
    // console.log(startIndex, stopIndex);
    return new Promise(async resolve => {
      const res = await API.get('/houses', {
        params: {
          ...this.filters,
          cityId: this.cityId,
          // 分页参数
          start: startIndex,
          end: stopIndex
        }
      })

      const { list, count } = res.data.body
      this.setState({
        // 注意：此处应该是追加数据，而不是覆盖数据！！！
        list: [...this.state.list, ...list],
        count
      })

      // 在发送请求获取到数据后，来完成Promise
      resolve()
    })
  }
  renderHouseList() {
    const {count, isLoaded} = this.state
    if (isLoaded && !count) return <NoHouse>没有找到房源，换个筛选条件试试</NoHouse>
    return (
      <div className={styles.houseItems}>
        {/* 根据筛选条件展示的房源列表 */}
        <InfiniteLoader isRowLoaded={this.isRowLoaded} loadMoreRows={this.loadMoreRows} rowCount={count}>
          {({ onRowsRendered, registerChild }) => (
            <WindowScroller>
              {
                ({ height, isScrolling, scrollTop }) => {
                  return (
                    <AutoSizer>
                      {({ width }) => (
                        <List
                          width={width}
                          height={height - 85}
                          rowCount={count}
                          rowHeight={ROW_HEIGHT}
                          rowRenderer={this.rowRenderer}
                          autoHeight
                          isScrolling={isScrolling}
                          scrollTop={scrollTop}
                          onRowsRendered={onRowsRendered}
                          ref={registerChild}
                        />
                      )}
                    </AutoSizer>
                  )
                }
              }
            </WindowScroller>
          )}
        </InfiniteLoader>
      </div>
    )
  }
  checkIsFixed = isFixed => {
    this.setState({isFixed})
  }
  render() {
    return (
      <div className={classNames(styles.houseList, { [styles.fixed]: this.state.isFixed})}>
        <Flex className={styles.header}>
          <i className="iconfont icon-back" onClick={() => this.props.history.go(-1)}></i>
          <SearcHearch className={styles.searchHeader} cityName={this.state.cityName}></SearcHearch>
        </Flex>
        {/* 筛选菜单栏 */}
        <Sticky height={40}>
          <Filter onFilter={this.onFilter} checkIsFixed={this.checkIsFixed}></Filter>
        </Sticky>
        {/* 条件渲染，有房源渲染房屋列表，无房源渲染NoHouse组件 */}
        {this.renderHouseList()}
      </div>
    )
  }
}
